const puppeteer = require('puppeteer')
const SITE = require('./config/site-config')
const fs = require('fs')
const getDateStr = require('./utils/date').getDateStr

const {
    loginName,
    password,
} = require('./config/passport.json')

const SELECTORS = require('./config/selectors')

!async function() {
  try {
    console.log('开始提交...')
    console.log(process.argv[2])
    const headless = (process.argv && process.argv[2] === '--headless') ? true : false

    const browser = await puppeteer.launch({
      headless
    })
    const page = await browser.newPage()

    // 登录
    await page.goto(SITE.url, {
      waitUntil: 'networkidle2'
    })
    await page.type(SELECTORS.LOGIN_USERNAME, loginName)
    await page.type(SELECTORS.LOGIN_PASSWORD, password)
    await page.click(SELECTORS.LOGIN_BUTTON)
    await page.waitForNavigation({
      waitUntil: 'networkidle2'
    })

    // 跳转项目目录
    await page.goto("https://dev-jira.shijicloud.com/browse/" + SITE.projectName, {
      waitUntil: 'networkidle2'
    })
    console.log('进入任务' + SITE.projectName)

    // 登录工作
    await page.click(SELECTORS.LOG_BUTTON)
    await page.click(SELECTORS.LOG_WORK)
    await page.waitFor(1000)

    // 获取根目录下的report.txt内容作为工作任务内容
    const report = await new Promise((resolve, reject) => {
      fs.readFile(__dirname + '/../report.txt', 'utf8', function (err, data) {
        if (err) reject(err)
        else
          resolve(data)
      })
    })
    console.log('获取工作日志内容: ')
    console.log(report)
    // 键入工作内容,依次为时长/开始时间/工作内容
    await page.type(SELECTORS.LOG_COST_TIME, SITE.loginDuration)
    // 1.TODO 根据格式写入当前的开始时间
    // 2.删除原有内容
    await page.type(SELECTORS.LOG_START_TIME, getDateStr())
    await page.keyboard.down('Shift')
    await page.keyboard.press('End')
    await page.keyboard.up('Shift')
    await page.keyboard.down('Backspace')
    await page.keyboard.up('Backspace')
    // 写入工作日志
    await page.type(SELECTORS.LOG_WORK_CONTENT, report)

    await page.click(SELECTORS.LOG_SUBMIT)
    console.log('提交工作任务')
    await page.waitForNavigation({
      waitUntil: 'networkidle2'
    })
    await browser.close()

  } catch (error) {
    console.log(error)
  }
}()